/**
 * form参数序列化为json格式
 * @param $
 */
(function($) {
    $.fn.serializeJson = function() {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function() {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
    $.fn.getInputData = function() {
    	var data = {};
    	this.find('input').each(function(){
    		data[$(this).attr('name')] = $(this).val();
    	});
    	return data;
    };
    $.fn.bindInput = function(rows) {
    	this.find('input').each(function(){
    		var input = $(this);
			var inputName = input.attr('name');
			for(var i =0 ;i<rows.length;i++){
	    		var row = rows[i];
	    		if(row.jian == inputName){
	    			input.val(row.val);
	    			break;
	    		} 
	    	}
    	});
    	return ;
    };
    
    $.fn.getAllData = function() {
    	var data = {};
    	this.find('input').each(function(){
    		if($(this).attr('type')=='text'){
    			data[$(this).attr('name')] = $(this).val();
    		}
    		if($(this).attr('type')=='checkbox'){
    			data[$(this).attr('name')] = $(this).prop('checked');
    		}
    	});
    	this.find('select').each(function(){
    			var name = $(this).attr('name');
    			if(name!=null&&name!=""){
    				data[name] = $(this).val();	
    			}
    			 
    	});
    	return data;
    };
    
    $.fn.bindModel = function(info) {
    	var data = {};
    	this.find('input').each(function(){
    		var name =  $(this).attr('name');
    		console.log(name);
    		for(key in info){
    			if(name==key){
    				$(this).val(info[key]);
    				break;
    			}
    		} 
    	});
    	return data;
    };
})(jQuery);
function getQueryString(name) { 
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return unescape(r[2]); return null; 
} 
function getQueryStringByDecode(name) { 
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return decodeURI(r[2]); return null; 
} 
/**
 * 返回DataGrid自动高度
 *
 * @returns {Number}
 */
function autoHeight() {
    if ($("#search_bar")) {
        return document.documentElement.clientHeight - $("#search_bar").outerHeight(true);
    } else {
        return document.documentElement.clientHeight;
    }
}

function widthPercent(percent){
	return (document.documentElement.clientWidth-52) * percent;
}
 
 
function messagerShow(message) {
    $.messager.show({
        title : '提示',
        msg : message,
        imeout : 1500,
        style : {
            right : '',
            top : document.body.scrollTop + document.documentElement.scrollTop,
            bottom : ''
        }
    });
}
 

function resetForm($form) {
    //jquery.validate插件验证错误信息清除
    $("input.error", $form).removeClass('error');
    $("label.error", $form).remove();
    $form.form('clear');
}

/**
 *时间格式化
 * @param {Object} fmt
 */
Date.prototype.format = function(fmt) {//author: meizz
    var o = {
        "M+" : this.getMonth() + 1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
/**
 *格式价格
 */
function currencyFormatted(amount) {
    var i = parseFloat(amount);
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) {
        s += '.00';
    }
    if (s.indexOf('.') == (s.length - 2)) {
        s += '0';
    }
    s = minus + s;
    return s;
}

/**
 * ajax请求反馈数据处理
 * @param {Object} data
 */
function feedback(data,dialog) {
    if ( typeof data == 'object') {
        if (data.result == "success") {
            if(dialog){
                dialog.dialog("close");
            }
            messagerShow(data.message);
        } else {
            $.messager.alert("结果", data.message);
        }
        refresh();
    } else if ( typeof data == 'string') {
        if (data.indexOf("用户权限不足") >= 0) {
            $.messager.alert("结果", "用户权限不足");
        } else if (data.indexOf("登陆") >= 0) {
            $.messager.alert('结果', '请重新<a href="' + window.location.href + '">登陆</a>');
        }
    } else {
        alert("状态异常，请尝试刷新，无效后联系开发人员");
    }
}


/**
 * ajax请求反馈数据处理
 * @param {Object} data
 */
function jsonResultFeedback(data,dialog) {
	console.log(data);
	if (data.code == 0) {
        if(dialog){
            dialog.dialog("close");
        }
        messagerShow(data.msg);
    } else {
        $.messager.alert("结果", data.msg);
    }
    refresh();
}

//TODO 所有开通城市缓存
var allCitysJson = "";
var allServicesModelJson = "";
(function ($) {
	$.fn.hkoMultiSelect  = function(setting){   
		var submit = setting.submit;
		var action = setting.action;
		var datas = setting.data;
		var noSel = setting.noSel;
		var sel = setting.sel; 
		var domDefaultName = 'hkoMultiSelectContainer';
		//TODO 属性刷新. 代码需要重构  
		if(action!=undefined || action != ''){
			domDefaultName += "-"+action;
			if(action=="city"){//codes
				if(allCitysJson==""){
					$.ajax({
			             type: "GET",
			             url: _webApp+'/commonData/getAllOpenCitys',
			             async:false,
			             dataType: "json",
			             success: function(res){
			            	 allCitysJson = res.data;
			             }      
			         });
				}  
				function getMultiSelectCitys(allCitys,citys){
					var sel = [];
					var noSel = [];  
					$.each(allCitys, function(n, c) {
						var isSelect = false;
						for(var i = 0;i<citys.length;i++){
							if((citys[i]+"")==c.cityCode){
								isSelect = true; 
							}
						}
						if(isSelect){
							sel.push({id:c.cityCode,value:c.cityName});
						}else{
							noSel.push({id:c.cityCode,value:c.cityName});
						}
				    }); 
					return {sel:sel,noSel:noSel};
				} 
				var multiCity = getMultiSelectCitys(allCitysJson,datas);
				sel = multiCity.sel;
				noSel = multiCity.noSel;
			}else if(action = "servicesModel"){//modelIds
				if(allServicesModelJson==""){
					$.ajax({
			             type: "GET",
			             url: _webApp+'/commonData/getAllServicesModels',
			             async:false,
			             dataType: "json",
			             success: function(res){
			            	 allServicesModelJson = res.data;
			             }      
			         });
				}   
				function getMultiSelectServicesModel(allModels,selectIds){
					var sel = [];
					var noSel = [];  
					$.each(allModels, function(n, m) {
						var isSelect = false;
						for(var i = 0;i<selectIds.length;i++){
							if((selectIds[i]+"")==m.id){
								isSelect = true; 
							}
						}
						console.log(m);
						var row = {id:m.id,value:m.name+""};
						if(isSelect){
							sel.push(row);
						}else{
							noSel.push(row);
						} 
				    }); 
					return {sel:sel,noSel:noSel};
				} 
				var multiModels = getMultiSelectServicesModel(allServicesModelJson,datas);
				sel = multiModels.sel;
				noSel = multiModels.noSel;
			}
		}   

		//TODO 前端性能可能比较差,如果每次都要重置的话.
		$("#"+domDefaultName).remove();
		if($("#"+domDefaultName).length <= 0){
			var sel_left = domDefaultName+'-sel_left';
			var sel_right = domDefaultName+'-sel_right';
			var btn_1 = domDefaultName+'-btn_1';
			var btn_2 = domDefaultName+'-btn_2';
			var btn_3 = domDefaultName+'-btn_3';
			var btn_4 = domDefaultName+'-btn_4';
			var btn_5 = domDefaultName+'-btn_5';
			var container = '<div id="'+domDefaultName+'" ';   
			container += 'style="display:none;position: absolute;background-color: #F5DAAE;font-family: Microsoft YaHei;z-index:10000;">';
			container += '<table><tr>';
			container += '<td><div>可选择</div><select multiple class="hkoMultiSelectContainerSel" id="'+sel_left+'">';
			 
			container += '</select></td>';
			container += '<td class="hkoMultiSelectContainerBtn"><p><button   id="'+btn_1+'">>></button></p><p><button  id="'+btn_2+'">></button></p><p><button  id="'+btn_3+'"><</button></p><p><button  id="'+btn_4+'"><<</button></p><p><button  id="'+btn_5+'">ok</button></p></td>';
			container += '<td><div>已选择</div><select multiple class="hkoMultiSelectContainerSel" id="'+sel_right+'">'
			  
			container += '</select></td>';
			container += '</tr></table> ';
			container += '</div>'; 
			$("body").append(container);
			
			function checkBtn() {
				jQuery("#"+sel_left+">option").length > 0 ? jQuery("#"+btn_1).removeAttr("disabled") : jQuery("#"+btn_1).attr("disabled", "disabled");
				jQuery("#"+sel_left+" option:selected").length > 0 ? jQuery("#"+btn_2).removeAttr("disabled") : jQuery("#"+btn_2).attr("disabled", "disabled");
				jQuery("#"+sel_right+" option:selected").length > 0 ? jQuery("#"+btn_3).removeAttr("disabled") : jQuery("#"+btn_3).attr("disabled", "disabled");
				jQuery("#"+sel_right+">option").length > 0 ? jQuery("#"+btn_4).removeAttr("disabled") : jQuery("#"+btn_4).attr("disabled", "disabled");
			}

			function clickBtn(e) {
				console.log(e.target.id);
				console.log(btn_1);
				if (btn_1 == e.target.id) {
					jQuery("#"+sel_left+">option").appendTo("#"+sel_right);
				} else if (btn_2 == e.target.id) {
					jQuery("#"+sel_left+" option:selected").appendTo("#"+sel_right);
				} else if (btn_3== e.target.id) {
					jQuery("#"+sel_right+" option:selected").appendTo("#"+sel_left);
				} else if (btn_4 == e.target.id) {
					jQuery("#"+sel_right+">option").appendTo("#"+sel_left);
				}
				checkBtn();
			} 
			$("#"+sel_left+",#"+sel_right).bind("change", checkBtn);
			$("#"+btn_1+",#"+btn_2+",#"+btn_3+",#"+btn_4+"").bind("click", clickBtn);
			checkBtn();  
			$('#'+btn_5).click(function(){
				$('#'+domDefaultName).hide();
				var items = [];
				$('#'+sel_right+' option').each(function(){
					items.push({id:$(this).val(),value:$(this).html()}); 
				});
				submit(items);
			});
		} 
		 
		$('#'+sel_left).empty(); 
		for (var i = 0 ;i<noSel.length;i++){
			$('#'+sel_left).append('<option value="'+noSel[i].id+'">'+noSel[i].value+'</option>'); 
		} 
		$('#'+sel_right).empty();
		for (var i = 0 ;i<sel.length;i++){
			$('#'+sel_right).append('<option value="'+sel[i].id+'">'+sel[i].value+'</option>');  
		} 
		
		//事件更新
		$(this).click(function(e){   
			var left ;
			var top ;
			left = $(this).offset().left+'px';
			top = $(this).offset().top+'px';
			$('#'+domDefaultName).css('left',left);
			$('#'+domDefaultName).css('top',top);
			$('#'+domDefaultName).show();  
			 
		});
		 
		
	};
})(jQuery); 